package com.yuqing.sentimentapp.login.acitivity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.yuqing.sentimentapp.MainActivity;
import com.yuqing.sentimentapp.R;
import com.yuqing.sentimentapp.base.BaseActivity;
import com.yuqing.sentimentapp.jpush.TagAliasOperatorHelper;
import com.yuqing.sentimentapp.login.bean.LoginResultBean;
import com.yuqing.sentimentapp.login.presenter.LoginPresenter;
import com.yuqing.sentimentapp.login.presenter.impl.LoginPresenterImpl;
import com.yuqing.sentimentapp.login.view.LoginView;
import com.yuqing.sentimentapp.utils.SharePrefrenceHelper;
import com.yuqing.sentimentapp.utils.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

public class VerifyCodeActivity extends BaseActivity implements LoginView<LoginResultBean>{

    @BindView(R.id.tv_send_tip)
    TextView mTvSendTip;
    @BindView(R.id.et_1)
    EditText mEt1;
    @BindView(R.id.et_2)
    EditText mEt2;
    @BindView(R.id.et_3)
    EditText mEt3;
    @BindView(R.id.et_4)
    EditText mEt4;
    @BindView(R.id.btn_login)
    Button mBtnLogin;
    private String phoneNum;
    private EditText[] mArray;
    private LoginPresenter loginPresenter;
    private String verifyCode;

    @Override
    public int getLayoutId() {
        return R.layout.activity_verify_code;
    }

    @Override
    public void initPresenter() {
        loginPresenter = new LoginPresenterImpl(this);
    }

    @Override
    public void initView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            phoneNum = bundle.getString("phoneNum");
            mTvSendTip.setText(String.format(getString(R.string.login_sms_tips), phoneNum));
        }
        initListener();
        resetFocues();
    }

    private void initListener() {
        mArray = new EditText[]{mEt1, mEt2, mEt3, mEt4};
        for (int i = 0; i < mArray.length; i++) {
            final int j = i;
            mArray[j].addTextChangedListener(new TextWatcher() {
                private CharSequence temp;

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    temp = s;
                }

                @Override
                public void afterTextChanged(Editable s) {

                    if (temp.length() == 1 && j >= 0 && j < mArray.length - 1) {
                        mArray[j + 1].setFocusable(true);
                        mArray[j + 1].setFocusableInTouchMode(true);
                        mArray[j + 1].requestFocus();
                    }

                    if (temp.length() == 0) {
                        if (j >= 1) {
                            mArray[j - 1].setFocusable(true);
                            mArray[j - 1].setFocusableInTouchMode(true);
                            mArray[j - 1].requestFocus();
                        }
                    }
                    checkNumber();
                }
            });
            mArray[j].setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (hasFocus) {
                        if (j > 0 && TextUtils.isEmpty(mArray[j - 1].getText().toString())) {
                            resetFocues();
                        }
                    }
                }
            });
            mArray[j].setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_DEL
                            && event.getAction() == KeyEvent.ACTION_DOWN) {
                        onKeyDelete();
                        return true;
                    }
                    return false;
                }
            });
        }
    }

    private void onKeyDelete() {
        for (int i = 0; i < mArray.length; i++) {
            mArray[i].setText("");
        }
        mArray[0].setFocusable(true);
        mArray[0].setFocusableInTouchMode(true);
        mArray[0].requestFocus();
    }

    private void resetFocues() {
        for (int i = 0; i < mArray.length; i++) {
            if (TextUtils.isEmpty(mArray[i].getText().toString())) {
                mArray[i].setFocusable(true);
                mArray[i].setFocusableInTouchMode(true);
                mArray[i].requestFocus();
                break;
            }
        }
    }

    public void checkNumber() {
        if (!TextUtils.isEmpty(mEt1.getText().toString().trim()) && !TextUtils.isEmpty(mEt2.getText().toString().trim()) && !TextUtils.isEmpty(mEt3.getText().toString().trim()) && !TextUtils.isEmpty(mEt4.getText().toString().trim())) {
            verifyCode = mEt1.getText().toString().trim() + mEt2.getText().toString().trim() + mEt3.getText().toString().trim() + mEt4.getText().toString().trim();
            mBtnLogin.setEnabled(true);
        }
    }

    @OnClick(R.id.btn_login)
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btn_login:
                loginPresenter.loginRequest(phoneNum, verifyCode);
                break;
        }
    }

    private void turnToMain() {
        MainActivity.start(this);
    }

    @Override
    public void onSuccess(LoginResultBean data) {
        if (data == null) return;
        LoginResultBean.DataBean dataBean = data.getData();
        if (dataBean == null) return;
        LoginResultBean.DataBean.UserBean user = dataBean.getUser();
        if (user == null) {
            ToastUtil.showShort("用户信息获取失败，请重试");
            return;
        }
        SharePrefrenceHelper.setUser(user);
        LoginResultBean.DataBean.UserBean.DeptVoBean deptVo = user.getDeptVo();
        if (deptVo != null) {
            SharePrefrenceHelper.setIsVip(deptVo.isIsVip());
        }
        SharePrefrenceHelper.setLoginStatus(true);
        SharePrefrenceHelper.setLoginMobile(phoneNum);
        SharePrefrenceHelper.setLoginResultBean(data);
        SharePrefrenceHelper.setToken(dataBean.getToken());
        if (JPushInterface.isPushStopped(getApplicationContext())) {
            JPushInterface.resumePush(getApplicationContext());
            //设置极光推送alias
            setJpushAlias();
        }
        turnToMain();
    }

    private void setJpushAlias() {
        TagAliasOperatorHelper.getInstance().handleAction(this, TagAliasOperatorHelper.ACTION_SET, TagAliasOperatorHelper.getInstance().getTagAliasBean(phoneNum));
    }

    @Override
    public void onFailure(String msg) {
        ToastUtil.showShort(msg);
    }
}
